/*
*┌─────────────────────────────────┐
*│　描   述：
*│　类   名：Jelly
*│　创  建  人：DD
*│　Copyright(C) 2020 by DD
*└─────────────────────────────────┘
*┌─────────────────────────────────┐
*│　修  改  人：
*│　修改方向：
*└─────────────────────────────────┘
*/
using UnityEngine;

namespace DD{
	public class Jelly : MonoBehaviour
	{
        public float Intensity = 1f;
        public float Mass =1f;
        public float stiffness = 1f;
        public float damping=1f;

		private Mesh OriginalMesh,MeshClone;
		private MeshRenderer renderer;
        private JellyVertex[] jy;
        private Vector3[] vertexArray;

        private void Start( )
        {
            OriginalMesh = GetComponent<MeshFilter> ().sharedMesh;
            MeshClone = Instantiate ( OriginalMesh );
            GetComponent<MeshFilter> ().sharedMesh = MeshClone;
            renderer = GetComponent<MeshRenderer> ();

            jy = new JellyVertex[MeshClone.vertices.Length];
            for ( int i = 0 ; i < MeshClone.vertices.Length ; i++ )
            {
                jy[i] = new JellyVertex ( i , transform.TransformPoint ( MeshClone.vertices[i] ) );
            }

        }
        private void FixedUpdate( )
        {
            vertexArray = OriginalMesh.vertices;
            for ( int i = 0 ; i < jy.Length ; i++ )
            {
                Vector3 target = transform.TransformPoint(vertexArray[jy[i].ID]);
                float intensity = (1-(renderer.bounds.max.y-target.y)/renderer.bounds.size.y)*Intensity;
                jy[i].Shake ( target , Mass , stiffness , damping );
                target = transform.InverseTransformPoint ( jy[i].Position );
                vertexArray[jy[i].ID] = Vector3.Lerp ( vertexArray[jy[i].ID] , target , intensity );
            }
            MeshClone.vertices = vertexArray;
        }


        public class JellyVertex
        {
            public int ID;
            public Vector3 Position;
            public Vector3 velocity,force;
            public JellyVertex(int _id,Vector3 _pos)
            {
                ID = _id;
                Position = _pos;
            }
            public void Shake (Vector3 target , float m, float s,float d)
            {
                force = ( target - Position ) * s;
                velocity = ( velocity + force / m ) * d;
                Position += velocity;
                if ( ( velocity + force + force / m ).magnitude < 0.001f )
                    Position = target;
            }
        }
    }
}